package svc

import (
	"github.com/go-redis/redis/v8"
	"github.com/zeromicro/go-zero/core/logx"
	"go-zero-demo/distributed-id-rpc/internal/config"
	"go-zero-demo/distributed-id-rpc/internal/dao"
	"go-zero-demo/distributed-id-rpc/internal/initialize/mysql"
	redis2 "go-zero-demo/distributed-id-rpc/internal/initialize/redis"
	"go-zero-demo/distributed-id-rpc/internal/service/impl"
	"gorm.io/gorm"
)

type ServiceContext struct {
	Config         config.Config
	DBEngin        *gorm.DB
	RedisClient    *redis.Client
	SegmentUseCase *impl.SegmentUseCase
}

func NewServiceContext(c config.Config) *ServiceContext {
	// init DB ..
	db, dbErr := mysql.InitMysqlDB(c.Mysql)
	s := &ServiceContext{}
	s.Config = c
	if dbErr != nil {
		logx.Errorf("init mysql error:%s!", dbErr.Error())
		return s
	}
	// init Redis ..
	initRedis, redisErr := redis2.InitRedis(c.Redis)
	if redisErr != nil {
		logx.Errorf("init redis error:%s!", redisErr.Error())
		return &ServiceContext{
			Config:  c,
			DBEngin: db,
		}
	}
	useCase := impl.NewSegmentUseCase(db, initRedis, dao.NewSegmentRepo())
	return &ServiceContext{
		Config:         c,
		DBEngin:        db,
		RedisClient:    initRedis,
		SegmentUseCase: useCase,
	}
}
